<?php

namespace common\models;

use Yii;
use yii\db\Expression;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "Article".
 */
class Article extends ActiveRecord {

    // 推荐类型常量定义
    const TypeIndex = 1;
    const TypeRecommend = 2;
    // 推荐类型常量描述
    public static $typeSelector = [
        self::TypeIndex => ['title' => '首页展示', 'status' => 'green'],
        self::TypeRecommend => ['title' => '热门推荐', 'status' => 'blue'],
    ];

    // only define rules for those attributes that
    // will receive user inputs.
    public function rules()
    {
        return [
            [['category_id', 'title', 'content', 'author', 'come', 'image'], 'required'],
            [['category_id'], 'integer'],
            [['title', 'image'], 'string', 'max' => 128],
            [['author', 'come'], 'string', 'max' => 32],
            [['tags'], 'match', 'pattern' => "/^([^;]{1,6};){0,4}([^;]{1,6})?$/"],
            [['content'], 'string', 'max' => 65535],
        ];
    }
    /**
     * @name 字段名称
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'category_id' => '分类',
            'types' => '推荐类型',
            'title' => '标题',
            'author' => '作者',
            'come' => '来源',
            'image' => '图片',
            'content' => '内容',
            'tags' => '标签',
        ];
    }
    // @name 前端js验证 逻辑
    // @param $encodeJson boolean 是否转成JSON字符串
    public static function flyer($type = 'update')
    {
        $rule = [
            'param' => [
                'category_id' => ['分类', ['int', 'required']],
                'types' => ['推荐类型', ['int']],
                'title' => ['标题', ['maxlength' => 128, 'required']],
                'author' => ['作者', ['maxlength' => 32, 'required']],
                'come' => ['来源', ['maxlength' => 32]],
                'image' => ['图片', ['maxlength' => 128]],
                'content' => ['内容', ['maxlength' => 65535, 'required']],
                'tags' => ['标签', ['tags']],
            ],
        ];
        return $rule;
    }

    /**
     * @name before save article rebuild insert params
     * @param $insert object 文章模型
     * @return boolean
     */
    public function beforeSave($insert)
    {
        // 插入前
        // 添加/修改 管理员
        $this->admin_id = Yii::$app->admin['id'];
        // 父操作
        return parent::beforeSave($insert);
    }

    /**
     * @name after save article resave tags
     * @param $insert object 文章模型
     * @param $changedAttributes array 改变的属性
     * @param boolean
     */
    public function afterSave($insert, $changedAttributes)
    {
        // 保存数据之后，配置 Tag标签
        return parent::afterSave($insert, $changedAttributes) && ArticleTag::updateTags($this->id, $this->tags);
    }

    /**
     * @name 获取文章的分类
     * @return object
     */
    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'category_id']);
    }

    /**
     * @name 获取文章相关标签列表
     * @return object list
     */
    public function getArticleTags()
    {
        return $this->hasMany(ArticleTag::className(), ['article_id' => 'id']);
    }
    
    /**
     * @name 上传新图片时删除老图片
     * @param $image string 老图片路径
     * @return bool
     */
    public function unlinkImage($image)
    {
        if(empty($image) || ($image == $this->image)) {
            return true;
        }
        @unlink(Yii::getAlias('@upload/'.$image));
        return true;
    }

    // @name 获取指定类型的推荐文章信息 - 前端列表展示使用
    // @param $type int 推荐类型
    // @return array
    public static function findByType($type)
    {
        return Article::find()->select('id, title, view, image, content, created_at')
            ->where(new Expression('types & '.$type.' > 0'))
            ->orderBy('id desc')
            ->limit(8)
            ->asArray()->all();
    }
}
